/* eslint-disable  */
import { Device } from "@/api/interface/iot";
import DialogBox from "@/components/DialogBox";
import Empty from "@/components/Empty";

import { findScada } from "@/api/modules/scada/service";
import EmptyTopoBg from "@/assets/images/topo/topo-bg.png";
import { productModel } from "@/enums/dictEnum";
import { filePrefix } from "@/hooks/useSystem";
import { TopoType, useTopo } from "@/hooks/useTopo";
import { PublicStore } from "@/stores/modules/public";
import { Dict, getDictList } from "@/utils/cacheUtil";
import { confirm, showMsg, showTips } from "@/utils/util";
import { dayjs, ElMessageBox } from "element-plus";
import { ComponentInternalInstance, getCurrentInstance, PropType } from "vue";
import "./../model.scss";
import axios from "axios";

export const ViewTypePage = "page";
export const ViewTypeTopo = "topo";
export const ViewTypeCustom = "custom";
export default defineComponent({
	props: {
		disabled: Boolean,
		product: {
			type: Object as PropType<Device.ResProduct | any>,
			default() {
				return {};
			}
		}
	},
	emits: ["submit"],
	setup(props, { emit }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		let { getTopoServer, addTopoInfo, delTopoInfo, gotoTopoEditer } = useTopo();
		const selectedDialog = reactive({
			visible: false,
			pageData: {
				dataList: [] as any
				// page: 1,
				// pageSize: 4,
				// total: 1
			},
			pageDataCustom: {
				dataList: [] as any
				// page: 1,
				// pageSize: 4,
				// total: 1
			}
		});
		// 动态引入 @/components/Sansan/Model/views 路径下所有组件
		// 注意 组件必须要有名字，否则过滤掉
		const modulesFiles = import.meta.glob("@/components/Sansan/Model/views/**/*.tsx", { eager: true });
		const modulesFiles1 = import.meta.glob("@/components/Sansan/Model/views/**/*.tsx");
		let res_components = {} as any;
		res_components = markRaw(res_components);
		Object.keys(modulesFiles).forEach(item => {
			let comp = modulesFiles[item] as any;
			let name = comp.default.name;
			if (name) {
				selectedDialog.pageData.dataList.push({
					label: comp.default.label,
					img: comp.default.image,
					view: comp.default.name,
					type: ViewTypePage
				});
				res_components[name] = defineAsyncComponent(modulesFiles1[item] as any);
			}
		});
		const state = reactive({
			detail: {} as Device.ResProduct,
			viewTypeList: [] as Dict[],
			category: ViewTypePage,
			categoryList: [
				{
					label: proxy?.$t("viewconfig.category_label.page"),
					value: ViewTypePage
				},
				{
					label: proxy?.$t("viewconfig.category_label.topo"),
					value: ViewTypeTopo
				},
				{
					label: proxy?.$t("viewconfig.category_label.custom"),
					value: ViewTypeCustom
				}
			] as Select[],
			viewType: computed(() => {
				if (state.detail.view?.curr == ViewTypePage) {
					let item: any = state.detail.view?.page?.[0];
					let page: any = item && Object.values(item)[0];
					return page?.url;
				} else if (state.detail.view?.curr == ViewTypeCustom) {
					return state.detail.view?.custom.url;
				} else {
					let item: any = state.detail.view?.topo?.[0];
					return item?.topoId;
				}
			}),
			componentsList: res_components
		});
		watchEffect(() => {
			state.detail = JSON.parse(JSON.stringify(props.product));
		});
		onMounted(async () => {
			state.viewTypeList = await getDictList("view_type");
			axios.get(`${import.meta.env.DEV ? "/" : ""}config.json`).then((res: any) => {
				if (res.status == 200 && res.data) {
					selectedDialog.pageDataCustom.dataList = res.data.customDataList.map(item => {
						return { ...item, type: ViewTypeCustom, view: `${item.view}${item.url ? encodeURIComponent(item.url) : ""}` };
					});
				}
			});
		});
		const showView = () => {
			selectedDialog.visible = true;
		};
		const changeView = ({ view, type }: { view: string; type: string }) => {
			let info: any = {};
			if (type == ViewTypeTopo) {
				//组态视图
				state.detail.view = { curr: ViewTypeTopo, page: [], topo: [{ topoId: view }] };
			} else if (type == ViewTypeCustom) {
				state.detail.view = { curr: ViewTypeCustom, custom: { url: view } };
			} else {
				//页面视图
				info[view] = { url: view, type: type };
				state.detail.view = {
					curr: ViewTypePage,
					page: [{ ...info }],
					topo: []
				};
			}
		};
		const cleanView = () => {
			state.detail.view = {};
			submit();
		};
		const submit = () => {
			emit("submit", { ...props.product, ...state.detail });
			selectedDialog.visible = false;
		};
		const changeCategory = () => {
			if (state.category == ViewTypeTopo) {
				findScada({
					sourceType: TopoType.product,
					sourceId: state.detail.model
				}).then(res => {
					state.componentsList = res.result;
				});
			} else {
				state.componentsList = res_components;
			}
		};
		const addNewTopo = () => {
			ElMessageBox.prompt(proxy?.$t("viewconfig.elmsg.label"), proxy?.$t("viewconfig.elmsg.title"), {
				confirmButtonText: proxy?.$t("viewconfig.elmsg_btn.confirm"),
				cancelButtonText: proxy?.$t("viewconfig.elmsg_btn.cancel"),
				inputPlaceholder: proxy?.$t("viewconfig.elmsg.placeholder"),
				inputValue: props.product.name,
				draggable: true
			}).then(({ value }) => {
				addTopoInfo({
					label: state.detail.model + "-" + dayjs().format("YYYYMMDD"),
					sourceId: state.detail.model,
					sourceType: TopoType.product,
					deptId: state.detail.deptId
				}).then((res: any) => {
					let ok = showTips(res.code, "组态配置操作", res.message);
					if (ok) {
						changeCategory();
					}
				});
			});
		};
		const deleteTopo = (topo: any) => {
			if (topo.sourceId != state.detail.model) {
				showMsg("当前数据不支持删除。", false);
				return;
			}
			confirm({ content: "删除后无法找回，确定删除当前组态？" }).then(flag => {
				if (!flag) {
					return;
				}
				delTopoInfo(topo).then(res => {
					let ok = showTips(res.code, "删除组态", res.message);
					if (ok) {
						changeCategory();
					}
				});
			});
		};
		const gotoTopo = (topo: any) => {
			gotoTopoEditer(topo.id);
		};
		return () => {
			return (
				<div class="h-full relative" style={"overflow: hidden;"}>
					{props.disabled ? null : (
						<div class="absolute right-4 top-4 z-10">
							{state.viewType ? (
								<el-popconfirm width="300px" title="确定移除产品的可视化页面？" onConfirm={cleanView}>
									{{
										reference: () => {
											return <el-button type="danger">移除配置</el-button>;
										}
									}}
								</el-popconfirm>
							) : null}
							<el-button type="primary" onClick={showView} class="ml-4">
								{proxy?.$t("viewconfig.btn.change")}
							</el-button>
						</div>
					)}
					<DialogBox
						title={proxy?.$t("viewconfig.dialog_title.select_template")}
						v-model:visible={selectedDialog.visible}
						onConfirm={submit}
						class="dialog-dense"
					>
						<div class="pl-8 pr-8" style="height:70vh">
							<el-radio-group v-model={state.category} class="h-14" onChange={changeCategory}>
								{state.categoryList.map(item => {
									return <el-radio label={item.value}>{item.label}</el-radio>;
								})}
							</el-radio-group>
							{state.category == ViewTypePage ? (
								<>
									<div class="flex flex-wrap overflow-auto" style="height: calc(100% - 100px);">
										{selectedDialog.pageData.dataList.map((item: any) => {
											return (
												<el-card
													class={[
														"bg-gray-100 relative m-[1%] w-[30%] h-[30%]",
														state.detail?.view?.page?.find(info => (Object.values(info)[0] as any).url == item.view)
															? "card-item-active"
															: null
													]}
													onClick={() => changeView(item)}
												>
													<el-image src={item.img} fit="fill" lazy class="h-full w-full" />
													<el-tag type="" class="absolute top-0 left-0">
														{item.label}
													</el-tag>
												</el-card>
											);
										})}
									</div>
									{/* <el-pagination
										class="mt-2 justify-end"
										v-model:current-page={selectedDialog.pageData.page}
										v-model:page-size={selectedDialog.pageData.pageSize}
										page-sizes={[6, 24, 48, 90, 300]}
										small
										layout="total, sizes, prev, pager, next"
										total={selectedDialog.pageData.total}
									/> */}
								</>
							) : null}
							{state.category == ViewTypeTopo ? (
								<div
									class={state.componentsList.length > 1 ? "grid grid-cols-2 gap-8 overflow-auto" : "w-full"}
									style="height: calc(100% - 75px);"
								>
									{!state.componentsList.length ? (
										<Empty
											onAdd={addNewTopo}
											title={proxy?.$t("viewconfig.add_topo_empty.title")}
											subtitle={proxy?.$t("viewconfig.add_topo_empty.subtitle")}
										/>
									) : (
										state.componentsList.map((topo: any) => {
											return (
												<div class={["bg cover-img h-full", state.componentsList.length > 1 ? "flex" : "w-full"]}>
													<el-card
														class={[
															"h-full bg-gray-100 relative w-full",
															state.detail.view?.topo?.find((t: any) => t.topoId == topo.id) ? "card-item-active" : null
														]}
														onClick={() => changeView({ view: topo.id, type: ViewTypeTopo })}
													>
														{topo.cover ? (
															<img src={`${filePrefix()}${topo.cover}`} class="flex-1" style="width:100%;height:100%" />
														) : topo.defaultCover ? (
															<img src={`${filePrefix()}${topo.defaultCover}`} class="flex-1" style="width:100%;height:100%" />
														) : (
															<img src={EmptyTopoBg} class="flex-1" style="width:100%;height:100%" />
														)}
														<el-tag type="" class="absolute top-0 left-0">
															{topo.label}
														</el-tag>
														<div class="absolute config-topo">
															<el-button
																type="danger"
																onClick={(e: Event) => {
																	e.stopPropagation();
																	deleteTopo(topo);
																}}
															>
																删除组态
															</el-button>
															<el-button
																type=""
																onClick={(e: Event) => {
																	e.stopPropagation();
																	gotoTopo(topo);
																}}
															>
																配置组态
															</el-button>
														</div>
													</el-card>
												</div>
											);
										})
									)}
								</div>
							) : null}
							{state.category == ViewTypeCustom ? (
								<>
									<div class="flex flex-wrap overflow-auto" style="height: calc(100% - 100px);">
										{selectedDialog.pageDataCustom.dataList.map((item: any) => {
											return (
												<el-card
													class={[
														"bg-gray-100 relative m-[1%] w-[30%] h-[30%]",
														state.detail?.view?.custom?.url == item.view ? "card-item-active" : null
													]}
													onClick={() => changeView(item)}
												>
													<el-image src={item.img} fit="fill" lazy class="h-full w-full" />
													<el-tag type="" class="absolute top-0 left-0">
														{item.label}
													</el-tag>
												</el-card>
											);
										})}
									</div>
									{/* <el-pagination
										class="mt-2 justify-end"
										v-model:current-page={selectedDialog.pageDataCustom.page}
										v-model:page-size={selectedDialog.pageDataCustom.pageSize}
										page-sizes={[6, 24, 48, 90, 300]}
										small
										layout="total, sizes, prev, pager, next"
										total={selectedDialog.pageDataCustom.total}
									/> */}
								</>
							) : null}
						</div>
					</DialogBox>
					{!state.viewType ? (
						<div class="h-full flex items-center" style="margin-top:-5%">
							<Empty subtitle={proxy?.$t("viewconfig.empty.subtitle")}>
								{{
									btns: () => {
										return props.disabled ? null : (
											<el-button type="primary" onClick={showView}>
												{proxy?.$t("viewconfig.empty_btn.showview")}
											</el-button>
										);
									}
								}}
							</Empty>
						</div>
					) : (
						<div class="w-full h-full" style={"overflow-y: auto;"}>
							{!state.viewType ? null : state.detail.view?.curr == ViewTypePage ? (
								h(state.componentsList[state.viewType], {
									is6210: state.detail.model == productModel.ss6210,
									isHmp: state.detail.model == productModel.hmp
								})
							) : state.detail.view?.curr == ViewTypeTopo ? (
								<>
									<iframe
										src={
											`${getTopoServer()}/topo/#/visual/show?id=${state.viewType}&dataType=pc-data&token=` + PublicStore().token
										}
										frameborder="0"
										class="w-full h-full"
									></iframe>
								</>
							) : state.detail.view?.curr == ViewTypeCustom ? (
								<>
									<iframe
										src={`${state.viewType}${RegExp(/\?.+=.*/).test(state.viewType) ? "&" : "?"}token=${PublicStore().token}`}
										frameborder="0"
										class="w-full h-full"
									></iframe>
								</>
							) : null}
						</div>
					)}
				</div>
			);
		};
	}
});
